#pragma once
#include "rocksdb/slice.h"
#include "util/coding.h"
#include "db/dbformat.h"

namespace rocksdb {
    class MvccKey {
    public:
        Slice userKey_;
        Slice timestamp_;
        uint64_t seqNumAndType_;

    public:
        inline bool parseKey(Slice buf) {
          assert(!buf.empty());

          seqNumAndType_ = DecodeFixed64(buf.data() + buf.size() - 8);
          if (buf.size() == 8) {
              userKey_ = Slice(buf.data(), 0);
              timestamp_ = Slice(buf.data(), 0);
              return true;
          }
          Slice mvccKey = Slice(buf.data(), buf.size() - 8);
          const char ts_size = mvccKey[mvccKey.size() - 1];
          if ((size_t) ts_size >= mvccKey.size()) {
            std::cout << "WARN: cannot parse key: " << buf.data() << ", ts_size "
                      << (size_t) ts_size << " larger than length: " << mvccKey.size() << std::endl;
            userKey_ = mvccKey;
            timestamp_ = Slice(buf.data(), 0);
            return true;
          }
          userKey_ = Slice(mvccKey.data(), mvccKey.size() - ts_size - 1);
          timestamp_ = Slice(userKey_.data() + userKey_.size(), ts_size);

          return true;
        }

        void dump() const {
          std::cout << "userkey:" << userKey_.ToString(true) << " (" << userKey_.size() << "), timestamp:"
                    << timestamp_.ToString();
          uint64_t seq;
          ValueType t;
          UnPackSequenceAndType(seqNumAndType_, &seq, &t);
          std::cout <<", seq:" << seq << ", valuetype:" << t << std::endl;
        }
    };
}